# -*- coding: UTF-8 -*-
import Jetson.GPIO as GPIO
import time
import Adafruit_SSD1306
from PIL import Image, ImageDraw, ImageFont

# 设置GPIO模式为BOARD模式
GPIO.setmode(GPIO.BOARD)

# 指定使用的GPIO引脚
button_pin = 7

# 设置GPIO引脚为输入模式，上拉电阻使其默认高电平
GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# 去抖动处理
debounce_time = 0.3
last_button_state = GPIO.input(button_pin)
last_change_time = time.time()

# 初始化OLED屏幕
disp = Adafruit_SSD1306.SSD1306_128_64(rst=None, i2c_bus=1, gpio=GPIO)
disp.begin()

# 清空屏幕
disp.clear()
disp.display()

# 创建图像
width, height = disp.width, disp.height
image = Image.new('1', (width, height))
draw = ImageDraw.Draw(image)
font_size = 20  # 根据实际需求调整字体大小

# 使用PIL库加载自定义字体
font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
font = ImageFont.truetype(font_path, font_size)

try:
    print("开始测试")
    while True:
        button_state = GPIO.input(button_pin)
        
        if button_state != last_button_state and time.time() - last_change_time > debounce_time:
            if button_state == GPIO.LOW:
                text = 'suncheng'
                print(text)
                # 将文本输出到OLED屏幕
                draw.rectangle((0, 0, width, height), outline=0, fill=0)
                draw.text((5,height//2),text,font=font,fill=255)
                disp.image(image)
                disp.display()
            
            last_button_state = button_state
            last_change_time = time.time()

        time.sleep(0.7)
	# 清空屏幕
        disp.clear()
        disp.display()


except KeyboardInterrupt:
    pass

finally:
    GPIO.cleanup()
    disp.clear()
    disp.display()
    print("测试结束")
